package CBBOT::AI;

use strict;
use warnings;
use lib '/home/services/cbbot/irclib';
use lib '/home/services/cbbot/';
use CBBOT::Config;
use LWP::Simple;
use Encode;

my $dbh	= CBBOT::Config::get_dbh();
my @return = ('', 0);

sub get_random_quote {
	my $sql = " 
		SELECT r1.id,msg FROM backlog AS r1 JOIN 
			(SELECT (RAND() * (SELECT MAX(id) FROM backlog)) AS id) AS r2
 			WHERE r1.id >= r2.id ORDER BY r1.id ASC LIMIT 1;";	

	my $sth = $dbh->selectrow_hashref($sql, undef);
	@return = ($sth->{msg}, $sth->{id});
	
	return @return;
}

sub get_next_quote {
	my $like = shift;
	my $sth = $dbh->selectrow_hashref("SELECT id, who FROM backlog WHERE msg LIKE '%$like%' ORDER BY RAND() LIMIT 1", undef);

	if(defined($sth->{id})) {
		$sth->{id}++;
		my $next = $dbh->selectrow_hashref("SELECT msg, who FROM backlog WHERE id=?", undef, $sth->{id});
		if($sth->{who} eq $next->{who}) {
			get_next_quote($like);
		} else {
			@return = ($next->{msg}, $sth->{id});
		}
	} else {
		@return = get_random_quote();
	}

	return @return;
}

sub make_sense {
	my $q = shift;
	$q =~ s/kylling(:|,)\s//;
	$q =~ s/, kylling(.?)$//;

	my @words = split(' ', $q);
	my $num = scalar(@words);

	if($num == 1) {
		if($q =~ /\?$/) {
			@return = get_next_quote($q);	
		}
	} else {
		if($q =~ /har|hva|hvem|hvilken|hvor|hvordan|hvorfor/ && $q =~ /\?$/) {
			my $verbs = get("http://www.lindaunwin.com/verbs.htm");
			$verbs = encode_utf8($verbs);
			
			for my $word (@words) {
				if(length($word) > 1) {
					if($verbs =~ /$word/ && $word ne 'det') {
						my $sth = $dbh->selectrow_hashref("SELECT id, msg FROM backlog WHERE msg LIKE '%$word%' ORDER BY RAND() LIMIT 1", undef);
						@return = ($sth->{msg}, $sth->{id});
					}				
				}
			}
		} else {
			my @max = (0,'');
			for my $word (@words) {
				if(length($word) > $max[0]) {
					$max[0] = length($word);
					$max[1] = $word;
				}
			}

			my $like = $max[1];
			my $sth = $dbh->selectrow_hashref("SELECT id, msg FROM backlog WHERE msg LIKE '%$like%' ORDER BY RAND() LIMIT 1", undef);
			@return = ($sth->{msg}, $sth->{id});
		}
	}	 

	if(length($return[0]) < 2) {
		@return = ("Jeg blir fortalt at det jobbes med meg!", 0);
	} else {
		if($return[0] =~ /((mikaanes|laka|patrio|mulla|kylling)(:|,)\s)(.*)$/i) {
			$return[0] = $3;
		}
	}

	return @return;
}

sub upvote_reply {
	my $id = shift;
	if($id != 0) {
		my $current_rating = get_rating($id);
		my $rating = ++$current_rating;
		$dbh->do("UPDATE backlog SET rating=$rating WHERE id=$id");
	}
}

sub downvote_reply {
	my $id = shift;
	if($id != 0) {
		my $current_rating = get_rating($id);
		my $rating = --$current_rating;
		$dbh->do("UPDATE backlog SET rating=$rating WHERE id=$id");
	} 
}

sub get_rating {
	my $id = shift;
	my $r = $dbh->selectrow_hashref("
		SELECT rating FROM backlog WHERE id=?", undef, $id);
	return $r->{rating};
}

1;

